package com.strongbj.iot.devices.dam.response.handle.v1;

import java.net.InetSocketAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.dam.message.DAMMessage;
import com.strongbj.iot.devices.dam.message.MQMessageOfDAM;
import com.strongbj.iot.devices.smarrack.response.entity.DeviceEntity;
import com.strongbj.iot.mq.producer.TopicSender;

import io.netty.channel.ChannelHandlerContext;
/**
 * 初始化完成
 * @author yuzhantao
 *
 */
public class InitCompleteHandle extends DAMV1Handle {
	private static Logger logger = LogManager.getLogger(DoorStateHandle.class.getName());
	private static final byte COMMAND=0x02;
	private final static String DEVICE_ONLINE_ACTION_CODE = "device_online"; // 设备在线的code
	private final static String RFID_TYPE = "damDc";
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	
	@Override
	public Object handle(ChannelHandlerContext ctx, DAMMessage t) {
		InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
		String ip = insocket.getAddress().getHostAddress();
		logger.info("DAM设备 初始化完成 IP={}",ip);
		pushDeviceOnlineMessageToMQ(ByteUtil.byteArrToHexString(t.getAddressCode()),ip);
		return null;
	}

	@Override
	protected boolean isHandleDAMMessage(DAMMessage t) {
		if(t.getCommand()==COMMAND){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 推送设备联机信息到MQ
	 */
	private void pushDeviceOnlineMessageToMQ(String deviceCode, String ip) {
		MQMessageOfDAM msg = new MQMessageOfDAM(); 
		msg.setActioncode(DEVICE_ONLINE_ACTION_CODE);
		msg.setDevType(RFID_TYPE);

		DeviceEntity dev = new DeviceEntity();
		dev.setDeviceCode(deviceCode);
		dev.setIp(ip);
		msg.setAwsPostdata(dev);
		String json = JSON.toJSONString(msg);
		topicSender.send("damCommandToService", json);
		logger.info("上传DAM设备初始化在线信息=" + json);
	}
}
